package com.simen.hellobytes.android.image;

import android.graphics.*;
import android.graphics.drawable.Drawable;
import com.simen.hellobytes.IOUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * author: SimenHi
 * create time: 2020-04-24 15:24
 * description:
 */
public class BitmapUtil {

    /**
     * drawable转bitmap
     *
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) // drawable 转换成bitmap
    {
        int width = drawable.getIntrinsicWidth();// 取drawable的长宽
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;// 取drawable的颜色格式
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);// 建立对应bitmap
        Canvas canvas = new Canvas(bitmap);// 建立对应bitmap的画布
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);// 把drawable内容画到画布中

        return bitmap;
    }

    public static Bitmap createCircleImage(Bitmap source) {
        return createCircleImage(source, Bitmap.Config.ARGB_8888);
    }

    public static Bitmap createCircleImage(Bitmap source,Bitmap.Config config) {
        float width = source.getWidth();
        float height = source.getHeight();
        float min = Math.min(width,height);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);

        Bitmap target = Bitmap.createBitmap((int) min, (int) min, config);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(min / 2, min / 2, min / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);

        return target;
    }

    public static void recycleBmp(Bitmap bitmap){
        if(bitmap!=null && !bitmap.isRecycled()){
            bitmap.recycle();
        }
    }

    public static void bitmapToJpegFile(Bitmap bitmap, File jpegFile) throws IOException {
        bitmapToImageFile(bitmap, Bitmap.CompressFormat.JPEG,90,jpegFile);
    }

    public static void bitmapToImageFile(Bitmap bitmap,Bitmap.CompressFormat format, int quality, File imageFile) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        bitmap.compress(format,quality,byteArrayOutputStream);
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream(imageFile);
            fileOutputStream.write(byteArrayOutputStream.toByteArray());
        }  finally {
            IOUtil.closeSilently(byteArrayOutputStream);
            IOUtil.closeSilently(fileOutputStream);
        }
    }

}
